package com.diamond.web.service.system;

import java.util.List;

import org.springframework.stereotype.Service;

import com.diamond.web.model.system.Permission;
import com.diamond.web.service.GenericService;

@Service
public class PermissionService extends GenericService<Permission,Long> {

    @SuppressWarnings("unchecked")
	public List<Permission> selectPermissionsByRoleId(Long roleId) {
    	String hql = "select r.permissions From Role r where r.id=:roleId";
        return createQuery(hql).setParameter("roleId", roleId).list();
    }

	public List<Permission> selectListByParentId(Long pid) {
		StringBuffer  hql = new StringBuffer("From Permission ");
		if(pid==null){
			hql .append(" where parent is null");
		}else{
			hql.append("where parent.id=?");
		}
		return findForList(hql.toString(), pid);
	}

	public List<Permission> selectMenuList(Long uid) {
		
		return null;
	}

	/**
	 * 查找所有权限标示
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> selectAllSign() {
		String hql = "select p.permissionSign from Permission p";
		return createQuery(hql).list();
	}

	public Permission addSubPermission(Permission model) {
		model.setIsMenu(false);
		insert(model);
		return model;
	}

	public void updateSubPermission(Permission model) {
		Permission p = selectById(model.getId());
		p.setParent(model.getParent());
		p.setPermissionName(model.getPermissionName());
		p.setPermissionSign(model.getPermissionSign());
		update(p);
	}

	@Override
	public List<Permission> selectList() {
		String hql="From Permission order by sort";
		return findForList(hql);
	}

	public void deletePermission(Long id) {
		String delSql = "delete from sys_role_permission where permissions_id=?"; //删除已经分配的关联的权限
		getSession().createSQLQuery(delSql).setLong(0, id).executeUpdate();
		this.deleteById(id);
	}
}
